package appfuse.framework.database;

import java.sql.ResultSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SqlUtil {
	private Log log = LogFactory.getLog(this.getClass());
	
	/**
	 * 得到新Id
	 * @return
	 */
	public int getNewId(String tableName){
    	int iResult = 0;
    	String sql = "select table_id from table_id where table_name = '" + tableName + "'";
    	SqlCommand sqlCommand;
    	sqlCommand = new SqlCommand(sql);
    	
		try {
			ResultSet myRs = sqlCommand.executeQuery();
			if(myRs.next()){	//找到数据库
				iResult = myRs.getInt("table_id");
				sqlCommand.setSqlCommand("update table_id set table_id = table_id+1 where table_name = '" + tableName + "'");
				
			}else{	//找不到
				iResult = 1000;
				sql = "insert table_id(table_name,table_id) values(?,?)";
				sqlCommand.setSqlCommand(sql);
				
				sqlCommand.setString(1,tableName);
				sqlCommand.setInt(2,iResult+1);	//初始序号
				
				
				
			}
		    	
			sqlCommand.executeUpdate();
        }
        catch (Exception e) {
        	e.printStackTrace();
        	log.error("getNewId() error:" + e.getStackTrace());
        }
	 finally {
		sqlCommand.close();
		sqlCommand = null;
	}
        
        return iResult;
    }
	
	/**
	 * 验证某表是否存在某条记录
	 * @return
	 */
	public static boolean isExistInDB(String tableName, Integer id){
    	String sql = "select id from " + tableName + " where id = '" + id + "'";
    	SqlCommand sqlCommand;
    	sqlCommand = new SqlCommand(sql);
    	
		try {
			ResultSet myRs = sqlCommand.executeQuery();
			if(myRs.isFirst() || myRs.isLast()){
				return true;
			}			
        }
        catch (Exception e) {
        	e.printStackTrace();
        }
        
        return false;
    }

}
